/*
 * @Author: yangzonglong
 * @Date: 2021-03-01 13:18:46
 * @version: v1.0.0
 * @Descripttion:
 * @LastEditors: yangzonglong
 * @LastEditTime: 2023-07-22 17:39:39
 * @Auditor:
 */
import React, { useState, useImperativeHandle, forwardRef, useEffect, useCallback, useRef } from 'react';
import { Select } from '@library';
import { Form } from 'antd';
import { getQuery } from '../../util';
import useQueryControlWrap from '../../hooks/useQueryControlWrap';
import { CanvasItemProps } from '../../interface';
import { FormItemProps } from '../components/InputFormItemController';

export interface DataLinkItemProps extends CanvasItemProps {
  formItemProps?: FormItemProps;
  inputProps: any;
  disabled?: boolean;
  initialValue?: any;
  sendData?: any;
  scriptsChangeData?: any;
}

interface DataLinkComBoxRef {
  clearDataSource: Function | undefined;
}

interface RefProps {
  getData(): any;
}


const CombineNode = forwardRef((props: any, ref: React.Ref<DataLinkComBoxRef>) => {
  const { disabled, inputProps, setV, v, onChange, query, onDropdownVisibleChange, getCurrInterceptors } = props;
  const selectRef = useRef<{ clearDataSource: Function; }>(null);

  useImperativeHandle(ref, () => ({
    clearDataSource: selectRef.current?.clearDataSource
  }));

  const fieldNames = {
    label: inputProps?.showFieldName,
    value: inputProps?.filedShowName
  };

  const url = inputProps.serviceType === 'APP'
    ? inputProps.modulesName && inputProps.serviceModuleCode
      ? `/bk/api/${inputProps.serviceModuleCode}/${inputProps.modulesName}/find`
      : ''
    : inputProps.modulesUrl || '';

  const placeholder = disabled || inputProps?.disabled ? '' : localStorage.i18nextLng === 'en' ? inputProps?.placeholderEn : inputProps?.placeholder;;

  function _onChange(e: any, item: any) {
    const mapFileds = inputProps.mapFileds || {};

    for (let k in item) {
      if (item.hasOwnProperty(k))
        item[mapFileds[k] || k] = item[k];
    }

    setV(item);
    onChange(item ? [item] : []);
  }

  return (
    <Select
      ref={selectRef}
      rtnDataAfter={getCurrInterceptors?.(url)?.get}
      handleQuery={getCurrInterceptors?.(url)?.set}
      onDropdownVisibleChange={onDropdownVisibleChange}
      disabled={disabled || inputProps?.disabled}
      fieldNames={fieldNames}
      query={query}
      url={url}
      value={v?.[inputProps?.filedShowName] || ''}
      oValue={v}
      onChange={_onChange}
      placeholder={placeholder}
    ></Select>
  );
});

const App = (props: DataLinkItemProps, ref: React.Ref<RefProps>) => {
  const { initialValue, disabled, formItemProps, domComplete, inputProps, scriptsChangeData, setFieldsValue, ...canvasProps } = props;

  const count = useRef(0);
  const cacheData = useRef(scriptsChangeData[inputProps?.bindName]);

  const selectRef = useRef<DataLinkComBoxRef>(null);
  const [v, setV] = useState(undefined);
  const [query, setQuery] = useState({});

  useEffect(() => {
    if (initialValue && Array.isArray(initialValue)) setV(initialValue[0]);
    else if (initialValue && typeof initialValue === 'object') {
      setV(initialValue);
    }
  }, [initialValue]);

  useEffect(() => {
    if (count.current === 0) {
      count.current = 1;
    } else {
      if (JSON.stringify(cacheData.current) !== JSON.stringify(scriptsChangeData[inputProps?.bindName])) {
        cacheData.current = scriptsChangeData[inputProps?.bindName];
        setV(undefined);
        setFieldsValue?.({ [formItemProps!.name as string]: undefined });
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [scriptsChangeData[inputProps?.bindName], (formItemProps || {}).name]);

  const onDropdownVisibleChange = useCallback((open: boolean) => {
    if (open) {
      setQuery(getQuery(inputProps, scriptsChangeData));
    }
  }, [inputProps, scriptsChangeData,]);

  useQueryControlWrap(canvasProps.id, formItemProps?.name, domComplete);

  useImperativeHandle(ref, () => ({
    getData() {
      return v;
    },

    setData(initialValue: any) {
      if (initialValue && Array.isArray(initialValue)) { 
        setQuery(getQuery(inputProps, scriptsChangeData));
        setV(initialValue[0]); 
      }
      else if (initialValue && typeof initialValue === 'object') {
        setQuery(getQuery(inputProps, scriptsChangeData));
        setV(initialValue);
      }else if(initialValue === null) {
        setV(undefined);
        setQuery(getQuery(inputProps, scriptsChangeData));
      }
    },

    clearDataSource() {
      selectRef.current?.clearDataSource?.();
      setFieldsValue?.({ [formItemProps!.name as string]: undefined });
    }
  }));

  const label = localStorage.i18nextLng === 'en' ? formItemProps?.labelEn : formItemProps?.label;

  return (
    <Form.Item {...canvasProps} {...formItemProps} label={label}>
      <CombineNode
        getCurrInterceptors={props.getCurrInterceptors}
        ref={selectRef}
        disabled={disabled}
        onDropdownVisibleChange={onDropdownVisibleChange}
        inputProps={inputProps}
        query={query}
        setV={setV}
        v={v} />
    </Form.Item>
  );
};

export default forwardRef(App);
